<template>
  <main style="height:100%">
  <el-button type="primary" style="margin-bottom:15px" class="greenButton" @click="dleMany()">批量删除</el-button>
    <el-table
    ref="multipleTable"
      @selection-change="handleSelectionChange"
      :data="routeList"
      :header-cell-style="{borderRight:'none',backgroundColor:'#00BDAC',color:'#FFFFFF'}"
      border
      height="78%"
      style="width: 100%;border:1px solid #00BDAC;"
    >
    <el-table-column
      type="selection"
      width="55">
      </el-table-column>
     <el-table-column align="center" width="50px" type="index" :index="table_index" label="序号"></el-table-column>
      <el-table-column align="center" label="巡检路线" prop="routeName"  width="150px"></el-table-column>
      <el-table-column align="center" label="巡检时间段" prop="timerange"></el-table-column>
      <el-table-column align="center" label="巡检点" width="150px">
        <template slot-scope="scope">
          <span>{{scope.row.patrolPoint}}个</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="签到点" width="150px">
        <template slot-scope="scope">
          <span>{{scope.row.signPoint}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="管理" width="300px">
        <template slot-scope="scope">
          <el-button @click="handleEdit(scope.$index, scope.row)" class="greenButton" size="mini">编辑</el-button>
          <el-button @click="handleErWei(scope.$index, scope.row)" class="greenButton" size="mini">二维码</el-button>
          <el-button @click="handleDelete(scope.$index, scope.row)" size="mini"
                     style="background-color: #FB1C89;color: #FFFFFF;">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page.sync="currentPage"
      :page-size="pagesize"
      :total="listTotal"
      @current-change="handleCurrentChange"
      layout="total,prev, pager, next, jumper"
      next-text="下一页"
      prev-text="上一页"
    ></el-pagination>

    <el-dialog
      :show-close="false"
      :visible.sync="isShowEdit"
      class="edit-dialog"
      destroy-on-close
      width="1100px"
    >
      <div class="edit-dialog-title" slot="title">编辑巡检路线</div>
      <el-form :model="addRouteFormData" class="edit-form" label-width="100px">
        <el-form-item label="线路名称：">
          <el-input class="add-input" placeholder="请输入线路名称" v-model="addRouteFormData.routeName"></el-input>
        </el-form-item>
        <div :key="route.index" v-for="(route,index) in addRouteFormData.routes">
          <el-form-item :label="`${route.index}号巡检点：`">
            <!-- <el-input
              class="add-input"
              placeholder="输入巡检点名称"
              v-model="addRouteFormData.routes[index].pointName"
            ></el-input> -->
            <el-select v-model="addRouteFormData.routes[index].pointName" clearable placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.f_name"
                :value="item.id">
              </el-option>
            </el-select>
            <div class="add-green-text" v-if="index === 0">
              <img @click="addPatrolPoint" alt src="../../../../static/add.jpg"/>
              <img @click="reducePatrolPoint" alt src="../../../../static/cutdown.jpg"/>
              <span>添加删除巡检点</span>
            </div>
          </el-form-item>
          <el-form-item label label-width="80px">
            <el-form-item
              :key="signPoint.index"
              label="签到点："
              v-for="(signPoint,signIndex) in addRouteFormData.routes[index].signPoints"
            >
              <el-input
                class="add-sign-input"
                v-model="addRouteFormData.routes[index].signPoints[signIndex].name"
              ></el-input>
              <div
                class="add-green-text"
                v-if="signIndex === 0"
              >
                <img @click="addSignPoint(index,signIndex)" alt src="../../../../static/add.jpg"/>
                <img @click="reduceSignPoint(index,signIndex)" alt src="../../../../static/cutdown.jpg"/>
                <span>添加删除签到点</span>
              </div>
            </el-form-item>
          </el-form-item>
        </div>
        <el-form-item label="签到时间：">
          <el-time-picker
            class="add-input"
            end-placeholder="结束时间"
            is-range
            placeholder="选择时间范围"
            range-separator="至"
            start-placeholder="开始时间"
            v-model="addRouteFormData.timeRange"
          ></el-time-picker>
        </el-form-item>
      </el-form>

      <div slot="footer">
        <el-button @click="cancel" class="pinkButton" type="primary">取消</el-button>
        <el-button @click="submit" class="greenButton" type="primary">提交</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :show-close="false"
      :visible.sync="isShowErwi"
      class="edit-dialog"
      destroy-on-close
      width="1100px"
    >
      <el-table
        :data="listErwei"
        border
        style="width: 100%;border:1px solid #00BDAC;"
        height="95%"
        :header-cell-style="{borderRight:'none',backgroundColor:'#00BDAC',color:'#FFFFFF'}"
      >
        <el-table-column align="center" width="100px" label="序号">
          <template slot-scope="scope">
            <span>{{scope.$index+1}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="tower" width="150px" label="楼栋"></el-table-column>
        <el-table-column align="center" prop="point" label="签到点位置"></el-table-column>
        <el-table-column align="center" prop="time" width="200px" label="签到时间限制"></el-table-column>
        <el-table-column align="center" label="签到二维码下载" width="150px">
          <template slot-scope="scope">
            <el-button size="mini" class="greenButton" @click="actionDown(scope.$index, scope.row)">下载</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer">
        <el-button @click="cancelErwei" class="pinkButton" type="primary">取消</el-button>
      </div>
    </el-dialog>
  </main>
</template>

<script>
  import DayJs from 'dayjs';
  export default {
    data: function () {
      return {
        options:[],
        currentRouteId:'',
        currentPage: 1,
        pagesize: 10,
        listTotal: 1,
        isShowErwi:false,
        listErwei: [/*{
          id: 1,
          order: 1,
          tower: '1号楼',
          point: '三层501',
          time: '3:00-18:00',
          src: ''
        },
          {
            id: 2,
            order: 3,
            tower: '1号楼',
            point: '三层501',
            time: '3:00-18:00',
            src: ''
          }*/],
        routeList: [
          /*{
            routeName: "一号线",
            timerange: "8：00 - 10：00",
            patrolPoint: 3,
            signPoint: 6
          },
          {
            routeName: "二号线",
            timerange: "8：00 - 10：00",
            patrolPoint: 3,
            signPoint: 6
          },
          {
            routeName: "三号线",
            timerange: "8：00 - 10：00",
            patrolPoint: 3,
            signPoint: 6
          },*/
        ],

        isShowEdit: false,

        addRouteFormData: {
          routeName: "",
          routes: [
            {
              index: 1,
              pointName: "",
              signPoints: [
                {
                  index: 1,
                  name: ""
                }
              ],
              timeRange: []
            }
          ],
          tips: ""
        },
         multipleSelection:[],
      };
    },
    created() {
      this.getList();
    },
    mounted(){
    this.huoqu();
    },
    methods: {
      dleMany(){
      console.log(this.multipleSelection)
      if(this.multipleSelection.length==0){
        return this.$message.error('请选择您要删除的信息')
      }
      const arr = []
      this.multipleSelection.forEach((item)=>{
          arr.push(item.route_id)
      })
      console.log(arr.join(','))
      this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let parme = {
                id:arr.join(',')
              }
              console.log(parme)
              this.ajaxCommon.ajax({
                    url: 'piliangXGroutedelete',
                    data:parme,
                    success: (res) => {
                      console.log(res)
                      if(res.code == 200){
                        this.$message({
                            message: '删除成功',
                            type: 'success',
                            duration:'2000'
                          });
                          this.getList()
                      }else{
                        this.$message({
                            message: res.status,
                            type: 'error',
                            duration:'2000'
                          });

                      }
                     
                    }
                });
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });          
          });
    },
    handleSelectionChange(selection){
        console.log(selection)
        this.multipleSelection = selection
    },
      table_index(index){
        return (this.currentPage -1) * this.pagesize + index + 1
      },
      huoqu(){
      this.ajaxCommon.ajax({
          url: 'loulist',
          success: (res)=>{
            console.log(res)
            if(res.code == 200){
              this.options = res.data;
            }
          }
      })

    },
      getInfo(id, callback){
        this.ajaxCommon.ajax({
          url: 'traceInfo',
          urlConcat: id,
          success: (res) => {
            if (res.code == 200) {
              if(callback){
                callback(res.data);
              }
            }
          }
        })
      },
      getList(){
        this.ajaxCommon.ajax({
          url: 'traceList',
          data: {
            sort: 'DESC',
            page: this.currentPage
          },
          success: (res) => {
            if (res.code == 200) {
              var data = res.data;
              var list = data.map((item) => {
                Object.assign(item, {
                  routeName: item.route_name,
                  patrolPoint: item.route_point.length,
                  timerange: item.route_time,
                  signPoint: this.getSignNum(item.signed_point)
                });
                return item;
              });
              this.listTotal = res.total;
              this.routeList = list;
            }
            console.log(res)
          }
        })
      },
      cancelErwei(){
        this.isShowErwi = false
      },
      getSignNum: function (sign) {
        let num = 0;
        sign.forEach(item => {
          num += item.length
        });
        return num;
      },
      //分页
      handleCurrentChange(val) {
        this.currentPage = val;
        this.getList();
      },
      actionDown(index,row){
        console.log(index,row)
        ///create_qrcode?route_id=20&route_point_key=0&signed_point_key=0
        
        // if(row.src){
        //   this.downFile(row.src);
        //   console.log(11111111)
        // } else {
          var id = row.id;
          var keys = id.split('-');
          console.log('1111111',row,'--',{
              route_id: this.currentRouteId,
              route_point_key: keys[0],
              signed_point_key: keys[1]
            });
          this.ajaxCommon.ajax({
            url: 'traceGenErwei',
            data:{
              route_id: this.currentRouteId,
              route_point_key: keys[0],
              signed_point_key: keys[1]
            },
            success: (res) => {
              if (res.code == 200) {
                console.log(res.data);
                this.downFile(res.data);
              }
            }
          })
        // }
      },
      downFile(imgsrc, name='签到二维码'){
        var image = new Image();
        image.crossOrigin="anonymous";
        image.src=imgsrc
        image.onload = () => {  
        let imgUrl = this.getBase64Image(image)
         //window.navigator.msSaveOrOpenBlob判断是否是ie浏览器
          if (window.navigator.msSaveOrOpenBlob) {
              var bstr = atob(imgUrl.split(',')[1])
              var n = bstr.length
              var u8arr = new Uint8Array(n)
              while (n--) {
                u8arr[n] = bstr.charCodeAt(n)
              }
              var blob = new Blob([u8arr])
              window.navigator.msSaveOrOpenBlob(blob, imgsrc)
          } else {
              // 这里就按照chrome等新版浏览器来处理
              const alink = document.createElement('a')
              alink.href = imgUrl
              alink.download = imgsrc;
              alink.click()
              document.body.removeChild(alink)
          }
        }  
      },
      getBase64Image(img) {  
        var canvas = document.createElement("canvas");  
        canvas.width = img.width;  
        canvas.height = img.height;  
        var ctx = canvas.getContext("2d");  
        ctx.drawImage(img, 0, 0, img.width, img.height);  
        var ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase();  
        var dataURL = canvas.toDataURL("image/"+ext);
        return dataURL;  
      },
      upErwei(data){
        // console.log('336行',data);
        // let time = data.route_time;
        // let list = [];
        // data.route_point.forEach((item, index)=>{
        //   data.signed_point[index].forEach((sign, ii)=>{
        //     list.push({
        //       id: index+'-'+ii,
        //       tower: item,
        //       point: sign,
        //       time: time,
        //       src: data.qrcode_url[index][ii].trim()
        //     })
        //   })
        // });
        // console.log('350行',list);
        console.log('336行',data);
        let time = data.route_time;
        var list = [];
        console.log(data.route_point)
        data.route_point.map((item, index)=>{
          data.signed_point[index].map((items,indexs)=>{
            const obj = {
                  id: index+'-'+indexs,
                tower: item,
                point: data.signed_point[index][indexs],
                time: time,
                src: data.qrcode_url[index][indexs]==" "?data.qrcode_url[index][indexs]:' '
                
            }
            console.log(items)

              list.push(obj)
            console.log('obj',obj)
          })
        });
        this.listErwei = list;
      },
      handleErWei(index, row){
        this.isShowErwi = true;
        console.log(row);
        this.currentRouteId = row.route_id;
        this.getInfo(row.route_id,(data) => {
          console.log(data);
          this.upErwei(data);
        });
        console.log(row);
      },
      handleEdit(index, row) {
        console.log('编辑',row);
        let arr = []
        let arr1 = []
        var Y =  new Date().getFullYear() + '/'
        var M = (new Date().getMonth() + 1 < 10 ? '0' + (new Date().getMonth() + 1) : new Date().getMonth() + 1) + '/'
        var D = new Date().getDate() + ' '
        arr = row.timerange.split('~')
        let a = new Date(Y+M+D+' ' +arr[0])
        let b = new Date(Y+M+D+' ' +arr[1])
        arr1.push(a)
        arr1.push(b)
        var obj = {
          id: row.route_id,
          routeName: row.routeName,
          timeRange: arr1
        };
        console.log(JSON.stringify(obj))
        var routes = [];
        console.log(row);
        for (var i = 0; i < row.patrolPoint; i++) {
          var signs = [];
          for (var j = 0; j < row.signed_point[i].length; j++) {
            signs.push({
              index: j + 1,
              name: row.signed_point[i][j]
            })
          }
          routes.push({
            index: i + 1,
            pointName: Number(row.route_point_id1[i]),
            signPoints: signs
          })
        }
        obj.routes = routes;
        console.log('1111111111',JSON.stringify(obj))
        this.addRouteFormData = obj;
        console.log('最终编辑内容',this.addRouteFormData)
        /*console.log(row);
        * addRouteFormData: {
          routeName: "",
          routes: [
            {
              index: 1,
              pointName: "",
              signPoints: [
                {
                  index: 1,
                  name: ""
                }
              ],

            }
          ],
          timeRange: []
        }
        * */
        this.isShowEdit = true;
      },

      handleDelete(index, row) {
        var id = row.route_id;
        this.$confirm('将删除此巡检路线, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.ajaxCommon.ajax({
            url: 'traceDel',
            urlConcat: id,
            success: (res)=>{
              console.log(res);
              if(res.code==200){
                this.getList();
                console.log(this.routeList)
                this.ajaxCommon.notice('删除成功');
              } else {
                this.ajaxCommon.notice(res.status,3);
              }
            }
          });
        }).catch(() => {
          /*this.$message({
            type: 'info',
            message: '已取消删除'
          });*/
        });
      },

      addPatrolPoint() {
        this.addRouteFormData.routes.push({
          index: this.addRouteFormData.routes.length + 1,
          pointName: "",
          signPoints: [
            {
              index: 1,
              name: ""
            }
          ],
          timeRange: []
        });
      },

      reducePatrolPoint() {
        
        if (this.addRouteFormData.routes.length > 1) this.addRouteFormData.routes.pop()
        console.log(this.addRouteFormData)
      },

      addSignPoint(index, signIndex) {
        this.addRouteFormData.routes[index].signPoints.push({
          index: this.addRouteFormData.routes[index].signPoints.length + 1,
          name: ""
        });
      },

      reduceSignPoint(index, signIndex) {
        console.log(111111);
        if (this.addRouteFormData.routes[index].signPoints.length > 1){ 
          this.addRouteFormData.routes[index].signPoints.pop()
          }
      },
      //处理编辑的数据
      dealEditData: function (data) {
        console.log(JSON.stringify(data));
        var param = {
          route_name: data.routeName,
          route_point: [],
          signed_point: [],
          route_time: '',
          route_id: data.id,
          qrcode_url:[]
        };
        var routs = [];
        var signs = [];
        for(var i=0;i<data.routes.length;i++){
          var tRout = data.routes[i];
          routs.push(tRout.pointName);
          var arrayS = [];
          for(var j=0;j<tRout.signPoints.length;j++){
            var tSign = tRout.signPoints[j];
            arrayS.push(tSign.name);
          }
          signs.push(arrayS);
        }
        var dates = [];
        data.timeRange.forEach(item=>{
          dates.push(DayJs(item).format('HH:mm:ss'));
        });
        param.route_time = dates.join('~');
        param.route_point = routs;
        param.signed_point = signs;
        param.route_point.forEach((item,index)=>{
          const arr = []
          param.qrcode_url.push(arr)
          param.signed_point[index].forEach((items,indexs)=>{
            param.qrcode_url[index][indexs] = " "
          })
        })
        console.log('编辑之后数据',param)
        return param;
      },
      submit() {
        var param = this.dealEditData(this.addRouteFormData);
        console.log(param)
        this.ajaxCommon.ajax({
          url: 'traceEdit',
          method: 'post',
          data: param,
          success: (res)=>{
            if(res.code==200){
              this.ajaxCommon.notice('修改成功');
              this.isShowEdit = false;
              this.getList();
            } else {
              this.ajaxCommon.notice(res.status,2);
            }
            console.log(res);
          }
        })
      },

      cancel() {
        this.isShowEdit = false;
      }
    }
  };
</script>

<style lang="less" scoped>
  main {
    width: 100%;

    .edit-dialog-title {
      color: #ffffff;
      padding-left: 30px;
      height: 36px;
      line-height: 36px;
      font-size: 14px;
      background: #00bdac;
    }

    .add-input {
      width: 260px;
    }

    .add-sign-input {
      width: 180px;
    }

    .edit-form {
      width: 100%;

      .add-green-text {
        display: inline-flex;
        color: #00bdac;
        width: 160px;
        justify-content: space-between;
        align-items: center;
        vertical-align: bottom;
        margin-left: 14px;

        img {
          cursor: pointer;
          width: 22px;
          height: 22px;
        }
      }
    }

    .footer {
      display: flex;
      justify-content: space-between;
      margin-top: 30px;
    }
  }
</style>

<style lang="less">
  main {
    .edit-dialog {
      .el-dialog__header {
        padding: 0;
      }

      .el-dialog__body {
        padding: 30px;
        height: 450px;
        overflow: auto;
      }
    }
  }
</style>
